package com.leetcode;

import com.leetcode.common.TreeNode;

/**
 * 230. 二叉搜索树中第K小的元素
 * 中序遍历, 递归稍微不一样的写法
 *
 * @author fy
 * @date 2022/4/26 21:45
 */
public class Solution230_2 {

    private int count = 0;
    private int ans = -1;

    public int kthSmallest(TreeNode root, int k) {
        dfs(root, k);
        return ans;
    }

    private void dfs(TreeNode root, int k) {
        if (null == root || ans != -1) {
            return;
        }
        dfs(root.left, k);
        ++count;
        if (count == k) {
            ans = root.val;
        }
        dfs(root.right, k);
    }

}
